package com.riguz.forks.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

public final class JsonUtil {
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    private static final ObjectMapper mapper = new ObjectMapper();

    public static <T> String toJSON(T obj) {
        String jsonStr;
        try {
            jsonStr = mapper.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error("Failed to convert json:{}", e);
            throw new RuntimeException(e);
        }
        return jsonStr;
    }

    public static <T> T fromJSON(String json, Class<T> type) {
        T obj;
        try {
            obj = mapper.readValue(json, type);
        } catch (Exception e) {
            logger.error("Failed to parse json:{}", e);
            throw new RuntimeException(e);
        }
        return obj;
    }
}
